// www.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const PORT = 8080;
const checkSignature = require('./checkSignature');
const parseString = require('xml2js').parseString;

server.listen(PORT, () => {
    console.log(`正在监听${PORT}端口...`);
});

app.get('/', checkSignature);

app.post('/', (req, res) => {
  
    let body = '';
    req.on('data', data => {
        body += data;
    });
    req.on('end', () => {
        // console.log(body);
        // 解析xml消息
        parseString(body, function (err, result) {
            console.dir(result); //解析以后的对象
            console.dir(JSON.stringify(result));   //包装成json
            // console.dir(result.xml.Content[0]);    //只获取用户发过来的内容

            let {
                ToUserName,
                FromUserName,
                CreateTime,
                MsgType,
                Content,
                MsgId
            } = result.xml;

            const [FromUser] = ToUserName;
            const [toUser] = FromUserName;

            var CreateTime2 = parseInt(Date.now() / 1000);

            var reply = `<xml>
            <ToUserName><![CDATA[${toUser}]]></ToUserName>
            <FromUserName><![CDATA[${FromUser}]]></FromUserName>
            <CreateTime>${CreateTime2}</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[你发送的是${MsgType}类型的消息]]></Content>
            </xml>`;
            console.log(reply);
            res.send(reply);
        });
    })
});
